/**
 * @Author 天下无敌
 * @Date 
 * @AIDE AIDE+ 
 */
package com.ecs.core.gsystem;
import com.artemis.BaseEntitySystem;
import com.artemis.annotations.All;
import com.ecs.core.components.map.ChunkCom;
import com.ecs.core.gsystem.player.PlayerDataSystem;
import com.artemis.ComponentMapper;
import com.ecs.core.components.attribute.Transform;
import com.artemis.utils.IntBag;
import com.badlogic.gdx.math.Rectangle;
import com.ecs.core.components.player.NearTagCom;



@All({ChunkCom.class})
public class NearTagSystem extends BaseEntitySystem
{
	private PlayerDataSystem player;
	private ComponentMapper<Transform> transforms;
	private ComponentMapper<ChunkCom> chunks;
	private IntBag nearEntitys = new IntBag();//上一帧保存的实体id
	private IntBag nearChunk = new IntBag();//重叠区块
	private final Rectangle playerNearRect = new Rectangle();//玩家位置附近
	private final Rectangle entityRect = new Rectangle();//其他
	@Override
	protected void processSystem()
	{
	
		upPlayerNear();
		upNearEntitys();
		detectionAllChunk();
		int[] cids = nearChunk.getData();
		for(int i = 0;i < nearChunk.size();i++){
			detectionChunk(cids[i]);
		}
		
	}

	//判断上一帧的实体是否还存在玩家附近
	private void upNearEntitys(){
		int[] eids = nearEntitys.getData();
		for(int i = 0;i < nearEntitys.size();i++){
			int id = eids[i];
			
			if(!setUpEmtityRect(id)){ continue;}
			
			if(!playerNearRect.overlaps(entityRect)){
				nearEntitys.removeIndex(i);
				removeNear(id);
			}
		}
	}
	 
	//更新玩家附近范围
	public void upPlayerNear(){
		float playerX = (float)Math.floor(player.getPlayerCenterX());
		float playerY = (float)Math.floor(player.getPlayerCenterY());
		playerNearRect.set(
		playerX - 1,
		playerY - 1,
		3,3);
	}
	
	//获取与玩家重叠的区块
	private void detectionAllChunk(){
		nearChunk.clear();
		IntBag ens = this.subscription.getEntities();
		int[] eids = ens.getData();
		for(int i = 0;i < ens.size();i++){
			int id = eids[i];
			
			if(!setUpEmtityRect(id)){ continue;}
			
			if(playerNearRect.overlaps(entityRect)){
				nearChunk.add(id);
			}
		}
	}
	//遍历区块内实体
	private void detectionChunk(int e){
		ChunkCom chunk = chunks.get(e);
		int[] eids = chunk.activeEntityids.getData();
		for(int i= 0;i < chunk.activeEntityids.size();i++){
			int id = eids[i];
			
			if(!setUpEmtityRect(id)){ continue;}
			
			if(playerNearRect.overlaps(entityRect) && !nearEntitys.contains(id)){
				addNear(id);
				nearEntitys.add(id);
			}
		}
	}
	
	//设置矩阵
	public boolean setUpEmtityRect(int e){
		Transform tsf = transforms.get(e);
		if(tsf == null) return false;
		entityRect.set(tsf.getPosX(),
					   tsf.getPosY(),
					   tsf.getScaleX(),
					   tsf.getScaleY());
		return true;
	}
	
	private void removeNear(int p){
		world.getEntity(p).edit().remove(NearTagCom.class);
	}
	private void addNear(int p){
		world.getEntity(p).edit().create(NearTagCom.class);
	}
}
